﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Toolkit.Web.Infastructure;
using System.IO;

namespace Toolkit.Web.ExtensionMethods
{
    internal static class DelegateExtensions
    {
        internal static IHtmlString ToHtmlString(this Action<IViewComponentWriter> template)
        {
            IHtmlString result = null;

            if (template != null)
            {
                using (StringWriter writer = new StringWriter())
                {
                    template(new ViewComponentWriter(writer));
                    result = HtmlStringExtensions.Create(writer.ToString());
                    writer.Close();
                }
            }

            return result;
        }

        internal static IHtmlString ToHtmlString(this Action<object, IViewComponentWriter> template)
        {
            IHtmlString result = null;

            if (template != null)
            {
                using (StringWriter writer = new StringWriter())
                {
                    template(null, new ViewComponentWriter(writer));
                    result = HtmlStringExtensions.Create(writer.ToString());
                    writer.Close();
                }
            }

            return result;
        }

        internal static IHtmlString ToHtmlString(this Func<object, object> template, object parameter)
        {
            if (template == null) return null;
            return HtmlStringExtensions.Create(template(parameter).ToString());
        }

        internal static Action<IViewComponentWriter> ToActionDelegate(this Action<object, IViewComponentWriter> template, object parameter)
        {
            if (template == null) return null;
            return (writer) => { template(parameter, writer); };
        }

        internal static Action<IViewComponentWriter> ToActionDelegate(this Func<object, object> template, object parameter)
        {
            if (template == null) return null;
            return (writer) => { writer.Write(template(parameter).ToString()); };
        }

        internal static Action<IViewComponentWriter> ToActionDelegate<T>(this Action<T, IViewComponentWriter> template, T parameter)
        {
            if (template == null) return null;
            return (writer) => { template(parameter, writer); };
        }

        internal static Action<T, IViewComponentWriter> ToActionDelegate<T>(this Func<T, object> template)
        {
            if (template == null) return null;
            return (item, writer) => { writer.Write(template(item).ToString()); };
        }
    }
}
